<?php
namespace control;

/*
*排班表类
*/

class schedulerClass extends adIndexClass
{
    private const page = 'scheduler';
    private const table = 'roster';
    private const tableMx = 'roster_detail';
    private const title = '排班表';
    public array $weekArray = array("日", "一", "二", "三", "四", "五", "六");

    /*列表-查询条件*/
    public function home()
    {
        //生成查询表单
        $html =
            text(array("name" => "team", "title" => L('clock.table.kao_qin_zu'))) .
            selectMultiple(array("name" => "workDayId", "title" => L('clock.table.gong_zuo_ri'), "table" => "work_day", 'sqlField' => 'name', 'sqlId' => 'id')) .
            selectMultiple(array("name" => "member", "title" => L('clock.table.syry'), "table" => "staff", 'sqlField' => 'name', 'sqlId' => 'stid')) .
            text(array("name" => "createTime", 'class' => 'width200', 'laydate' => ['type' => 'date', 'range' => '~'], "title" => L('clock.table.geng_xin_ri_qi')));
        //返回
        return $this->homeFun($this->search($html));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "a.team" => $this->post('team'),//考勤组
            "member" => $this->post('member'),//适用人员
        );
        //全等查询数组
        $equal = array(
            "workDayId" => $this->post('workDayId'),//工作日
        );
        $and = "";
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), 'date', 'updateTime');
        }
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table . " as a join clock_rule as b on a.clockRuleId = b.id ", 'field' => " b.*,a.id as id,a.time,a.updateTime", "where" => $where, "order" => "a.time desc"));
        //获取表头
        $checkAll = $this->checkAll("listForm", "listId");
        $tr[] = array($checkAll, L('clock.table.kao_qin_zu'), L('clock.table.gong_zuo_ri'), L('clock.table.syry'), L('clock.table.cjsj'), L('clock.table.gxsj'));
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => L('clock.table.schedulerInfo'), "click" => "newIframe('" . L('clock.table.schedulerInfo') . "','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $workDay = query('work_day', " id = '$array[workDayId]'");

            $tr[] = array($this->dominate($dominate), $array['team'], $workDay['name'], self::findStaff(explode(',', $array['member'])), $array['time'], $array['updateTime']);
        }
        //控件
        $button = "";
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }


    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = L('clock.table.no_scheduler');
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
                'menu' => [
                    'edit' => L('clock.table.ji_ben_xin_xi'),
                    'schedule' => L('clock.table.pai_ban_ji_lu')
                ]
            );
            $mxButton = $scheduleButton = '';//明细按钮
            if ($this->power(self::page, "edit")) {
                $mxButton = "<span class='spanButton' style='margin-left:0' onclick=\"layer('" . self::page . "','addMx',{mainId:'" . $info['id'] . "'})\">新增</span><span class='spanButton' onclick=\"layer('" . self::page . "','operate',{id:'" . $info['id'] . "',act:'delMx'})\">" . L('clock.table.shan_chu') . "</span>";
                $scheduleButton = "<span class='spanButton' style='margin-left:0' onclick=\"layer('" . self::page . "','addSchedule',{mainId:'" . $info['id'] . "'})\">新增</span><span class='spanButton' onclick=\"layer('" . self::page . "','operate',{id:'" . $info['id'] . "',act:'delScheduleMx'})\">" . L('clock.table.shan_chu') . "</span>";
            }

            /******班次*******/
            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' and type = 1 order by time asc"));
            $checkAll = $this->checkAll("detailForm", "mxId");
            $tr[] = [$checkAll, L('clock.table.ban_ci'), L('clock.table.sxbsj')];
            foreach ($result['array'] as $val) {
                //列表控件
                $dominate = array(
                    "box" => array("name" => "mxId", "value" => $val['id']),
                    "edit" => array("title" => L('clock.table.bian_ji'), "click" => "layer('" . self::page . "','addMx',{mainId:'{$val['orderId']}',id:'{$val['id']}'})"),
                );
                $clockTime = find(['table' => 'clock_rule_time', 'field' => " group_concat(CONCAT_WS('-',startTime,if(endType,CONCAT_WS('','次日',endTime),endTime))) as clockTime", 'single' => " orderId = '$val[id]' and source = 1 group by orderId"]);
                $tr[] = [$this->dominate($dominate), $val['name'], $clockTime['clockTime']];
            }

            /******周期*******/
            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' and type = 2 order by time asc"));
            $checkAll = $this->checkAll("scheduleForm", "scheduleId");
            $scheduleTr[] = [$checkAll, L('clock.table.zqmc'), L('clock.table.zqts')];
            foreach ($result['array'] as $val) {
                //列表控件
                $dominate = array(
                    "box" => array("name" => "scheduleId", "value" => $val['id']),
                    "edit" => array("title" => L('clock.table.bian_ji'), "click" => "layer('" . self::page . "','addSchedule',{mainId:'{$val['orderId']}',id:'{$val['id']}'})"),
                );
                $scheduler = json_decode($val['scheduler'], true);
                $day = '';
                foreach ($scheduler as $v) {
                    if ($v == 'rest') {
                        $temp['name'] = L('clock.table.xiu_xi');
                    } else {
                        $temp = query(self::tableMx, " id = '$v'");
                    }
                    $day .= '-' . $temp['name'];
                }
                $day = ltrim($day, '-');
                $scheduleTr[] = [$this->dominate($dominate), $val['name'], count($scheduler) . '天为周期：' . $day];
            }

            $clockRule = query('clock_rule', " id = '$info[clockRuleId]'");
            $workDay = query('work_day', " id = '$clockRule[workDayId]'");
            //生成表单
            $data['html'] = $this->tableShow(array(
                array(
                    array(
                        L('clock.table.pbbbh') => $info['orderNo'],
                        L('clock.table.kao_qin_zu') => $clockRule['team'],
                        L('clock.table.gong_zuo_ri') => $workDay['name'],
                    ),
                    array(
                        L('clock.table.cjsj') => $info['time'],
                        L('clock.table.gxsj') => $info['updateTime'],
                    ),
                ),
                L('clock.table.ban_ci') => array(
                    array(
                        "<div>{$mxButton}</div>
                        <div class='purchaseMx' style='margin-top: 5px'><form name='detailForm'>" . hidden(array('name' => 'id', 'value' => $info['id'])) . $this->tableMany(array('tr' => $tr)) . "</form></div>"
                    ),
                ),
                L('clock.table.pai_ban_zhou_qi') => array(
                    array(
                        "<div>{$scheduleButton}</div>
                        <div class='purchaseMx' style='margin-top: 5px'><form name='scheduleForm'>" . hidden(array('name' => 'id', 'value' => $info['id'])) . $this->tableMany(array('tr' => $scheduleTr)) . "</form></div>"
                    ),
                ),
            ));
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        $html .= <<<efo
<script>
function addTimeRow(e){
    let total = 0;
    $(".clockTimeDiv ul").each(function (i){
        total++;
    });
    if (total>4){
        warn('最多设置5条');

    }else{
         $.post(root+'control/adIndex.html?cla=scheduler&fun=addTimeRow',{},function (res){
                $('.clockTimeDiv').append(res.data.html);
            },'json')
        }

}

function addScheduleRow(e){
     let total = 0;
    $(".scheduleDiv ul").each(function (i){
        total++;
    });
    let id = $("form[name='detailForm']").find("input[name='id']").val();
    // if (total>4){
    //     warn('最多设置5条');
    // }else{
         $.post(root+'control/adIndex.html?cla=scheduler&fun=addScheduleRow',{id:id},function (res){
                $('.scheduleDiv').append(res.data.html);
                reList();
            },'json')
        // }
}
//重新排序
function reList(){
     $(".scheduleDiv ul").each(function (i){
        $(this).find(".day").html('第'+(i+1)+'天')
    });
}
function decRow(e){
    $(e).parent().parent().parent().remove();
      reList();
}
</script>
efo;

        return $html;
    }

    /**
     * 生成周期中班次选项
     * @param $id
     * @return array
     */
    public function compositeOption($id): array
    {
        $option = [];
        $result = find(array('table' => self::tableMx, 'where' => " orderId = '$id' and type = 1 order by time asc"));
        foreach ($result['array'] as $array) {
            $option[$array['id']] = $array['name'];
        }
        $option['rest'] = L('clock.table.xiu_xi');
        return $option;
    }

    /**
     * 周期
     * @return bool|string
     */
    public function addSchedule()
    {

        $info = query(self::table, " id = '{$this->post('mainId')}'");
        $mx = query(self::tableMx, " id = '{$this->post('id')}'");

        $option = $this->compositeOption($info['id']);
        $clockTimeTr = '';
        $result['array'] = $mx['scheduler'] ? json_decode($mx['scheduler'], true) : [];
        if (is_array($result['array']) && count($result['array']) > 0) {
            foreach ($result['array'] as $k => $array) {
                if ($k == 0) {
                    $button = "<span style='margin-top: 0' class='spanButton' onclick='addScheduleRow(this)'>" . L('clock.table.add') . "</span>";
                } else {
                    $button = "<span style='margin-top: 0' class='spanButton' onclick='decRow(this)'>" . L('clock.table.shan_chu') . "</span>";
                }
                $clockTimeTr .=
                    "<div style='height: 40px'><ul><li style='float: left'><span class='day'>第" . ($k + 1) . "天</span>" . select(array('name' => 'scheduler[]', 'value' => $array, 'class' => 'text', 'title' => '请选择', 'option' => $option)) . "</li><li style='float: left'>{$button}</li></ul></div>";
            }
        } else {
            $clockTimeTr =
                "<div style='height: 40px'><ul><li style='float: left'><span class='day'>第1天</span>" . select(array('name' => 'scheduler[]', 'value' => '', 'class' => 'text', 'title' => '请选择', 'option' => $option)) . "</li><li style='float: left'><span style='margin-top: 0' class='spanButton' onclick='addScheduleRow(this)'>" . L('clock.table.add') . "</span></li></ul></div>";
        }
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                must . "周期名称：" => text(array("name" => "name", "value" => $mx['name'])),
            ),
            array(
                must . "周期天数：" => "<div class='scheduleDiv'>" . $clockTimeTr . "</div>"
            ),
        ),
            'hidden' => hidden(array('name' => 'mainId', 'value' => $this->post('mainId')))
        ));
        //返回
        return $this->layer(array("title" => L('clock.table.ban_ci_she_zhi'), "height" => 362, "html" => $html));
    }

    /**
     * 周期编辑
     */
    public function addScheduleEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $info = query(self::table, " id = '{$this->post('mainId')}'");
        $field = [
            'scheduler' => $this->post('scheduler') ? json_encode($this->post('scheduler'), 320) : [],
            'name' => $this->post('name'),
            'updateTime' => $this->time
        ];
        $annotation = [
            'name' => L('clock.table.zqmc'),
            'scheduler' => L('clock.table.zqts'),
        ];
        $rules = [
            'name' => 'required',
            'scheduler' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('clock.table.sch_edit_permission');
        } else {
            $where = " id = '$id' ";
            $mx = query(self::tableMx, $where);
            if (!$mx['id']) {
                $field = array_merge($field, [
                    'id' => $id,
                    'orderId' => $info['id'],
                    'type' => 2,
                    'time' => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::tableMx, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::tableMx,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "的排班周期， id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     * 添加打卡时间
     */
    public function addTimeRow()
    {
        $option = $this->createHourOption();

        $minuteOption = [];//分钟选项
        for ($i = 0; $i < 60; $i++) {
            $minuteOption[$i] = sprintf("%02d", $i);
        }
        $json['data']['html'] = "<div style='height: 40px'><ul><li style='float: left'>" . select(array('name' => 'startHour[]', 'change' => 'getSecHour', 'value' => '', 'class' => 'text', 'title' => '时', 'option' => $option)) . select(array('name' => 'startMinute[]', 'value' => '', 'class' => 'text', 'title' => '分', 'option' => $minuteOption)) . "\n至" .
            select(array('name' => 'endHour[]', 'value' => '', 'class' => 'text', 'title' => '时', 'option' => $option)) . select(array('name' => 'endMinute[]', 'value' => '', 'class' => 'text', 'title' => '分', 'option' => $minuteOption)) . "</li><li style='float: left'><span style='margin-top: 0' class='spanButton' onclick='decRow(this)'>" . L('clock.table.shan_chu') . "</span></li></ul></div>";
        return json_encode($json, 320);
    }

    /**
     * 添加排班周期
     * @return bool|string
     */
    public function addScheduleRow()
    {
        $option = $this->compositeOption($this->post('id'));
        $json['data']['html'] = "<div style='height: 40px'><ul><li style='float: left'><span class='day'></span>" . select(array('name' => 'scheduler[]', 'value' => '', 'class' => 'text', 'title' => '请选择', 'option' => $option)) . "</li><li style='float: left'><span style='margin-top: 0' class='spanButton' onclick='decRow(this)'>" . L('clock.table.shan_chu') . "</span></li></ul></div>";
        return json_encode($json, 320);
    }

    /**
     * 班次
     * @return bool|string
     */
    public function addMx()
    {
        $mx = query(self::tableMx, " id = '{$this->post('id')}'");
        /********打卡时间********/
        $clockTimeTr = '';
        $result = find(array('table' => 'clock_rule_time', "where" => " orderId = '$mx[id]' and source = 1  order by list asc"));
        $option = $this->createHourOption();


        $minuteOption = [];//分钟选项
        for ($i = 0; $i < 60; $i++) {
            $minuteOption[$i] = sprintf("%02d", $i);
        }

        if (is_array($result['array']) && count($result['array']) > 0) {
            foreach ($result['array'] as $k => $array) {

                if ($k == 0) {
                    $button = "<span style='margin-top: 0' class='spanButton' onclick='addTimeRow(this)'>" . L('clock.table.add') . "</span>";
                } else {
                    $button = "<span style='margin-top: 0' class='spanButton' onclick='decRow(this)'>" . L('clock.table.shan_chu') . "</span>";
                }
                $startItem = explode(':', $array['startTime']);
                $startType = $array['startType'] == 1 ? 'next-' : 'now-';
                $endItem = explode(':', $array['endTime']);
                $endType = $array['endType'] == 1 ? 'next-' : 'now-';
                $secOption = $this->createHourOption($startItem[0]);
                $clockTimeTr .=
                    "<div style='height: 40px'><ul><li style='float: left'>" . select(array('name' => 'startHour[]', 'change' => 'getSecHour', 'value' => $startType . $startItem[0], 'class' => 'text', 'title' => '时', 'option' => $option)) . select(array('name' => 'startMinute[]', 'value' => $startItem[1], 'class' => 'text', 'title' => '分', 'option' => $minuteOption)) . "\n至" .
                    select(array('name' => 'endHour[]', 'value' => $endType . $endItem[0], 'class' => 'text', 'title' => '时', 'option' => $secOption)) . select(array('name' => 'endMinute[]', 'value' => $endItem[1], 'class' => 'text', 'title' => '分', 'option' => $minuteOption)) . "</li><li style='float: left'>{$button}</li></ul></div>";
            }
        } else {
            $clockTimeTr =
                "<div style='height: 40px'><ul><li style='float: left'>" . select(array('name' => 'startHour[]', 'change' => 'getSecHour', 'value' => '', 'class' => 'text', 'title' => '时', 'option' => $option)) . select(array('name' => 'startMinute[]', 'value' => '', 'class' => 'text', 'title' => '分', 'option' => $minuteOption)) . "\n至" .
                select(array('name' => 'endHour[]', 'value' => '', 'class' => 'text', 'title' => '时', 'option' => $option)) . select(array('name' => 'endMinute[]', 'value' => '', 'class' => 'text', 'title' => '分', 'option' => $minuteOption)) . "</li><li style='float: left'><span style='margin-top: 0' class='spanButton' onclick='addTimeRow(this)'>" . L('clock.table.add') . "</span></li></ul></div>";
        }
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                must . L('clock.table.bcmc') . "：" => text(array("name" => "name", "value" => $mx['name'])),
            ),
            array(
                must . L('clock.table.sxbsj') . "：" => "<div class='clockTimeDiv'>" . $clockTimeTr . "</div>"
            ),
        ),
            'hidden' => hidden(array('name' => 'mainId', 'value' => $this->post('mainId')))
        ));
        $html .= <<<efo
<script>
 function getSecHour(e){
     let val = e.value;
     $.post(root+'control/adIndex.html?cla=scheduler&fun=getSecHour',{val:val},function(res) {
         $(e).parent().find("[name='endHour[]']").empty().append(res.option);
     },'json')
 }
</script>
efo;

        //返回
        return $this->layer(array("title" => L('clock.table.ban_ci_she_zhi'), "height" => 362, 'width' => 900, "html" => $html));
    }

    /**
     * 根据选择获取适合的排班时间
     * @return bool|string
     */
    public function getSecHour()
    {
        $val = $this->post('val');
        $hour = explode('-', $val);
        $json['option'] = option(array(
            "title" => "时",
            "option" => $this->createHourOption($hour[1]),
        ));
        return json_encode($json, 320);
    }

    /**
     * 创建时间选项
     * @param $start
     * @return array
     */
    public function createHourOption($start = 0): array
    {
        $option = [];//小时选项
        $startHour = $start;
        $flag = false;//次日标志
        for ($i = 0; $i < 24; $i++) {
            if ($startHour == 24) {
                //次日
                $startHour = 0;
                $flag = true;
            }
            if ($flag) {
                if ($startHour >= 0) {
                    $option['next-' . $startHour] = '次日' . $startHour;
                }
            } else {
                $option['now-' . $startHour] = $startHour;
            }
            $startHour++;
        }
        return $option;
    }


    /**
     * 班次编辑
     *
     * @return bool|string
     */
    public function addMxEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $info = query(self::table, " id = '{$this->post('mainId')}'");
        $startHourArr = $this->post('startHour');
        $startMinuteArr = $this->post('startMinute');
        $endHourArr = $this->post('endHour');
        $endMinuteArr = $this->post('endMinute');

        $field = [
            'name' => $this->post('name'),
            'updateTime' => $this->time
        ];
        $annotation = [
            'name' => L('clock.table.bcmc'),
        ];
        $rules = [
            'name' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('clock.table.sch_edit_permission');
        } else {
            $where = " id = '$id' ";
            $mx = query(self::tableMx, $where);
            if (!$mx['id']) {
                $field = array_merge($field, [
                    'id' => $id,
                    'orderId' => $info['id'],
                    'type' => 1,
                    'time' => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::tableMx, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::tableMx,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                delete(array('table' => 'clock_rule_time', 'where' => " orderId = '$id' and source = 1"));
                //类型为固定上下班时间  删除原来的数据
                if (is_array($startHourArr)) {
                    foreach ($startHourArr as $k => $val) {
                        $item = explode('-', $val);
                        $endHour = explode('-', $endHourArr[$k]);
                        insert(array(
                            'table' => 'clock_rule_time',
                            'field' => [
                                'id' => self::getId(),
                                'orderId' => $id,
                                'startType' => $item[0] == 'next' ? 1 : 0,
                                'startTime' => $item[1] . ':' . $startMinuteArr[$k],
                                'endType' => $endHour[0] == 'next' ? 1 : 0,
                                'endTime' => $endHour[1] . ':' . $endMinuteArr[$k],
                                'source' => 1,
                                'time' => $this->time
                            ]
                        ));
                    }
                }
                //添加日志
                $text = str_replace(['{{staffName}}', '{{team}}', '{{id}}'], [$this->control['name'], $info['orderNo'], $id], L('clock.table.sch_edit_text'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     * 排班记录
     */
    public function schedule()
    {
        //获取当前月的日历
        $toDate = $this->get('date') ?? $this->date;
        $json['html'] = $this->calendar($toDate, $this->get('id'));
        //返回
        return json_encode($json, 320);
    }

    public function calendar($date, $id): string
    {
        $_SESSION[self::page]['date'] = $date;
        $_SESSION[self::page]['id'] = $id;
        $month = date('Y-m', strtotime($date));
        $info = query(self::table, "id = '" . $id . "'");
        $clockRule = query('clock_rule', "id = '" . $info['clockRuleId'] . "'");
        //工作日
        $workDay = query('work_day', " id = '$clockRule[workDayId]'");
        $workDayArr = json_decode($workDay['workDay'], true);
        //总天数
        $days = date('t', strtotime($date));
        $dayHtml = "<tr class='no-edit'><td style='min-width: 50px'></td>";
        $weekHtml = "<tr class='no-edit'><td></td>";
        $lineHtml = "<tr class='no-edit'><td></td>";
        for ($i = 1; $i <= $days; $i++) {
            $dayHtml .= "<td>{$i}</td>";
            //判断当前日期是星期几
            $weekHtml .= "<td>" . $this->weekArray[date("w", strtotime(date('Y-m', strtotime($date)) . '-' . $i))] . "</td>";
            //间隔
            $lineHtml .= "<td>&nbsp;</td>";
        }
        $dayHtml .= "</tr>";
        $weekHtml .= "</tr>";
        $lineHtml .= "</tr>";
        $memberArr = [];
        $allStaff = find(array('table' => 'staff', 'where' => "workFlow = '已复核' and if(state='离职',date_format(quitDay,'%Y-%m') >= '$month',1=1)"));
        foreach ($allStaff['array'] as $array) {
            //根据员工选择器的值和当前员工的部门，职位，员工ID求交集
            $idColloection = $this->staffCombination(true, $array['stid']);
            $rule = query('clock_rule', " (concat(',',replace(selector,';',','),',') regexp concat(',',replace('{$idColloection}',',',',|,'),','))>0 and id = '$clockRule[id]'");
            if ($rule['id']) {
                $memberArr[] = $array['stid'];
            }
        }

        $peopleHtml = '';
        //存储班次总人数的数组
        $scheduleArr = [];
        $rosterMxAll = find(array('table' => self::tableMx, 'where' => " orderId = '$info[id]' and type = 1 order by time asc"));
        foreach ($rosterMxAll['array'] as $array) {
            $scheduleArr[] = ['id' => $array['id'], 'name' => $array['name']];
        }
        $totalScheduleArr = [];
        if (is_array($memberArr)) {
            foreach ($memberArr as $stid) {
                $staff = query('staff', " stid = '$stid'");
                $peopleHtml .= "<tr class='click-line'><td>{$staff['name']}</td>";
                for ($i = 1; $i <= $days; $i++) {
                    $toDay = date('Y-m', strtotime($date)) . '-' . sprintf("%02d", $i);//当前日期
                    $rosterSchedule = query('roster_schedule', " toDay = '$toDay' and stid = '$stid' and orderId = '$info[id]'");
                    if (!in_array($toDay, $workDayArr)) {
                        //节假日
                        $peopleHtml .= "<td class='rest-day' data-date='{$toDay}' data-stid='$stid' data-edit='0' data-id='rest'>休</td>";
                    } else {
                        if ($rosterSchedule['rosterMxId'] == 'rest') {
                            $word = '休';
                        } else {
                            $rosterMx = query(self::tableMx, " id = '$rosterSchedule[rosterMxId]'");
                            $word = mb_substr($rosterMx['name'], 0, 1, 'utf-8');
                        }
                        if ($toDay < $this->date) {
                            $edit = 0;
                            $class = 'rest-day';
                        } else {
                            $edit = 1;
                            $class = '';
                        }
                        $peopleHtml .= "<td class='{$class}' data-edit='{$edit}' data-date='{$toDay}' data-stid='$stid' data-id='{$rosterSchedule['rosterMxId']}'>{$word}</td>";
                    }
                    $totalScheduleArr[$rosterSchedule['rosterMxId']][$toDay] = $totalScheduleArr[$rosterSchedule['rosterMxId']][$toDay] ?? 0;
                    $totalScheduleArr[$rosterSchedule['rosterMxId']][$toDay] += 1;
                }
                $peopleHtml .= "</tr>";
            }
        }
        /******总计*****************/
        $totalHtml = '';
        $scheduleArr[] = ['name' => L('clock.table.xiu_xi'), 'id' => 'rest'];
        foreach ($scheduleArr as $val) {
            $totalHtml .= "<tr><td>{$val['name']}</td>";
            for ($i = 1; $i <= $days; $i++) {
                $toDay = date('Y-m', strtotime($date)) . '-' . sprintf("%02d", $i);//当前日期
                $totalScheduleArr[$val['id']][$toDay] = $totalScheduleArr[$val['id']][$toDay] ?? '';
                $totalHtml .= "<td>{$totalScheduleArr[$val['id']][$toDay]}</td>";
            }
            $totalHtml .= "</tr>";
        }
        $button = '';
        if ($this->power(self::page, "export")) {
            $button .= "  <a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportData'><span style='margin-left: 0' class='spanButton'>" . L('job.button.export') . "</span></a>\n";
        }

        return <<<eof
<div style="width: 95%;margin: 10px auto;padding: 0 20px">{$button}</div>
<div class="calendarBody">
<div class="calendarTitle"><span id="pre-button" class="pre-next-button" data-type="pre"><</span><span class="calendar-date">{$month}</span><input type="hidden" name="toDate" value="$date"><span id="next-button" data-type="next" class="pre-next-button" style="margin-left: 10px"> ></span></div>
<div class="calendarContent">
<input name="id" type="hidden" value="{$info['id']}">
<table class="dayTable">
{$dayHtml}
{$weekHtml}
{$peopleHtml}
{$lineHtml}
{$totalHtml}
</table>
</div>
</div>

<script>
 $(function() {
   $(".click-line td").click(function(e) {
       //清除弹窗
      clearDiv();
      $(".blueBackGroundColor").removeClass('blueBackGroundColor');
      let id = $("[name='id']").val();
      let edit = $(this).data('edit');
      let pageX = e.pageX;
      let pageY = e.pageY;
      if (edit ===1){
            let stid = $(this).data('stid');
            let date = $(this).data('date');
             $(this).addClass('blueBackGroundColor');
          //可编辑状态
          $.post(root+'control/adIndex.html?cla=scheduler&fun=getSelectSet',{id:id,pageX:pageX,pageY:pageY,stid:stid,date:date},function(res) {
                $(body).append(res.data.html);
          },'json');
      }
   });
     $("#next-button,#pre-button").click(function() {
        let type = $(this).data('type');
         let id = $("[name='id']").val();
         let date = $("[name='toDate']").val();
        $.post(root+'control/adIndex.html?cla=scheduler&fun=location',{type:type,id:id,date:date},function(res) {
            if(res.warn ==2){
                location.href = res.href;
            }else{
                warn(res.warn);
            }
        },'json')
     })
 })

//切换弹窗层tab条
function changeNav(e){
     let className =$(e).data('name');
     $(".choiceDivNav ul li").removeClass('show-li');
     $(e).addClass('show-li');
     $(".showContent").removeClass('showContent');
      $("."+className).addClass('showContent');
}
function setSchedule(e){
     let mxId = $(e).data('id');
     let type = $(e).data('type');
     let id = $("[name='id']").val();
     let stid = $(e).data('stid');
     let date = $(e).data('date');
       $.post(root+'control/adIndex.html?cla=scheduler&fun=setSchedule',{id:id,mxId:mxId,type:type,stid:stid,date:date},function(res) {
                if (res.warn===2){
                    location.href = res.href;
                }else{
                    warn(res.warn);
                }
          },'json');
}
 //点击非下拉区域隐藏
$(document).bind('click', function (e) {
    let target = $(".choiceDiv");
    if(!target.is(e.target) && target.has(e.target).length ===0){
      clearDiv();
    }
});
 function clearDiv(){
      $(".choiceDiv").remove();
 }
</script>

<style>
.calendarContent{
 width: 97%;
 margin: 0 auto;
 padding-bottom: 20px
}
.pre-next-button{
 cursor: pointer;
 margin-right: 10px;
 font-size: 19px;
 font-weight: bold
}
.calendar-date{
font-weight: bold;font-size: 17px
}
.calendarBody{
 width: 95%;
 border: 1px solid rgb(230, 230, 230);
 margin: 10px auto
}
.calendarTitle{
 width: 100%;
 height: 50px;
 text-align: center;
 line-height: 50px
}
.click-line td{
 cursor: pointer;
}
.choiceDiv{
  position: absolute;
 width: 170px;
 background-color: #FFFFFF;
 box-shadow: rgb(230 230 230) 5px 5px 3px;
}
.choiceDivNav{
 cursor: pointer;
 height: 35px;

}
.dayTable{
border-collapse: collapse;
    border-spacing: 0;
}
.dayTable td {
    border: 1px solid rgb(230, 230, 230);
    word-break: break-all;
}
.rest-day{
  background-color: #F2F2F2;
  color: gray;
}
.no-edit{
background-color: #F8F8F8
}
.choiceDivNav ul li {
 float: left;
 width: 47%;
 text-align: center;
 padding: 5px 2px;
}

.show-li{
 border-bottom: 2px solid #4C9CFB;
}
.choice-content ul li{
  padding: 3px 15px;
}
.choice-content ul li:hover {
    cursor: pointer;
    background-color: rgb(230, 230, 230);
}
.cycle-content ul li{
  padding: 3px 15px;
}
.cycle-content ul li:hover {
    cursor: pointer;
    background-color: rgb(230, 230, 230);
}
.choice-content,.cycle-content{
display: none;
}
.showContent{
 display: block;
}
.blueBackGroundColor{
  background-color: #4C9CFB !important;
  color:white;
}
</style>


eof;
    }

    /**
     * 导出
     */
    public function exportData()
    {
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = L('clock.table.nhmzdcdzx');
        } else {
            $data = [];
            $date = $_SESSION[self::page]['date'];
            $id = $_SESSION[self::page]['id'];
            $month = date('Y-m', strtotime($date));
            $info = query(self::table, "id = '" . $id . "'");
            $clockRule = query('clock_rule', "id = '" . $info['clockRuleId'] . "'");
            //工作日
            $workDay = query('work_day', " id = '$clockRule[workDayId]'");
            $workDayArr = json_decode($workDay['workDay'], true);
            $days = date('t', strtotime($date));
            $dayTr[] = '';
            $weekTr[] = '';
            $lineTr[] = '';
            for ($i = 1; $i <= $days; $i++) {
                $dayTr[] = $i;
                $weekTr[] = $this->weekArray[date("w", strtotime(date('Y-m', strtotime($date)) . '-' . $i))];
                $lineTr[] = '';
            }
            $data[] = $weekTr;

            $memberArr = [];
            $allStaff = find(array('table' => 'staff', 'where' => "workFlow = '已复核' and if(state='离职',date_format(quitDay,'%Y-%m') >= '$month',1=1)"));
            foreach ($allStaff['array'] as $array) {
                //根据员工选择器的值和当前员工的部门，职位，员工ID求交集
                $idColloection = $this->staffCombination(true, $array['stid']);
                $rule = query('clock_rule', " (concat(',',replace(selector,';',','),',') regexp concat(',',replace('{$idColloection}',',',',|,'),','))>0 and id = '$clockRule[id]'");
                if ($rule['id']) {
                    $memberArr[] = $array['stid'];
                }
            }
            //存储班次总人数的数组
            $scheduleArr = [];
            $rosterMxAll = find(array('table' => self::tableMx, 'where' => " orderId = '$info[id]' and type = 1 order by time asc"));
            foreach ($rosterMxAll['array'] as $array) {
                $scheduleArr[] = ['id' => $array['id'], 'name' => $array['name']];
            }
            $totalScheduleArr = [];
            if (is_array($memberArr)) {
                foreach ($memberArr as $stid) {
                    $staff = query('staff', " stid = '$stid'");
                    $temp = [];
                    $temp[] = $staff['name'];
                    for ($i = 1; $i <= $days; $i++) {
                        $toDay = date('Y-m', strtotime($date)) . '-' . sprintf("%02d", $i);//当前日期
                        $rosterSchedule = query('roster_schedule', " toDay = '$toDay' and stid = '$stid' and orderId = '$info[id]'");
                        if (!in_array($toDay, $workDayArr)) {
                            //节假日
                            $temp[] = '休';
                        } else {
                            if ($rosterSchedule['rosterMxId'] == 'rest') {
                                $word = '休';
                            } else {
                                $rosterMx = query(self::tableMx, " id = '$rosterSchedule[rosterMxId]'");
                                $word = mb_substr($rosterMx['name'], 0, 1, 'utf-8');
                            }
                            $temp[] = $word;
                        }
                        $totalScheduleArr[$rosterSchedule['rosterMxId']][$toDay] = $totalScheduleArr[$rosterSchedule['rosterMxId']][$toDay] ?? 0;
                        $totalScheduleArr[$rosterSchedule['rosterMxId']][$toDay] += 1;
                    }
                    $data[] = $temp;
                }
            }
            $data[] = $lineTr;
            /******总计*****************/
            $scheduleArr[] = ['name' => L('clock.table.xiu_xi'), 'id' => 'rest'];
            foreach ($scheduleArr as $val) {
                $temp = [];
                $temp[] = $val['name'];
                for ($i = 1; $i <= $days; $i++) {
                    $toDay = date('Y-m', strtotime($date)) . '-' . sprintf("%02d", $i);//当前日期
                    $totalScheduleArr[$val['id']][$toDay] = $totalScheduleArr[$val['id']][$toDay] ?? '';
                    $temp[] = $totalScheduleArr[$val['id']][$toDay];
                }
                $data[] = $temp;
            }
            $text = str_replace(['{{staffName}}', '{{month}}'], [$this->control['name'], $month], L('clock.table.sch_export_text'));
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($dayTr, $data, str_replace(['{{month}}'], [$month], L('clock.table.sch_export_name')) . ".xlsx");
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }

    /**
     * 上个月或下个月
     * @return bool|string
     */
    public function location()
    {
        $date = $this->post('date');
        $type = $this->post('type');
        $id = $this->post('id');
        if (empty($id)) {
            $json['warn'] = L('clock.table.wzdpbjl');
        } elseif (empty($type) || !in_array($type, ['pre', 'next'])) {
            $json['warn'] = L('clock.table.wzdtzlx');
        } elseif (empty($date)) {
            $json['warn'] = L('clock.table.wzddqrq');
        } else {
            if ($type == 'next') {
                $toDate = date('Y-m-d', strtotime("+1 month", strtotime(date('Y-m-01', strtotime($date)))));//下个月1号
            } else {
                $toDate = date('Y-m-d', strtotime("-1 month", strtotime(date('Y-m-01', strtotime($date)))));//下个月1号
            }

            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=scheduler&fun=detail&menu=schedule&date={$toDate}&id=" . $id;
        }
        return json_encode($json, 320);
    }

    /**
     * 设置班次
     */
    public function setSchedule()
    {
        $type = $this->post('type');
        $info = query(self::table, " id = '{$this->post('id')}'");
        $mx = query(self::tableMx, " id = '{$this->post('mxId')}' and type = '$type'");
        $staff = query('staff', " stid = '{$this->post('stid')}'");
        $date = $this->post('date');

        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = L('clock.table.sch_edit_permission');
        } elseif (empty($type)) {
            $json['warn'] = L('clock.table.wzdszlx');
        } elseif (empty($staff['stid'])) {
            $json['warn'] = L('clock.table.wzdcyg');
        } elseif (empty($info['id'])) {
            $json['warn'] = L('clock.table.wzdcpbb');
        } elseif ($this->post('mxId') != 'rest' && empty($mx['id'])) {
            $json['warn'] = L('clock.table.wzdcbc');
        } elseif (strtotime($date) === false) {
            $json['warn'] = L('clock.table.rqgscw');
        } else {

            if ($type == 1) {
                //排班记录
                $record = query('roster_schedule', " stid = '$staff[stid]' and toDay = '$date' and orderId = '$info[id]'");
                if (empty($record['id'])) {
                    //按班次排
                    $field = [
                        'id' => self::getId(),
                        'orderId' => $info['id'],
                        'stid' => $staff['stid'],
                        'toDay' => $date,
                        'rosterMxId' => $this->post('mxId'),
                        'updateTime' => $this->time,
                        'time' => $this->time
                    ];
                    $json['warn'] = static::insert(["table" => 'roster_schedule', "field" => $field]);
                    $record['id'] = $field['id'];
                } else {
                    //按班次排
                    $field = [
                        'toDay' => $date,
                        'rosterMxId' => $this->post('mxId'),
                    ];
                    $json['warn'] = static::update(["table" => 'roster_schedule', "field" => $field, 'where' => " id = '$record[id]'"]);
                }
                if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                    //添加日志
                    $text = str_replace(['{{staffName}}', '{{id}}'], [$this->control['name'], $record['id']], L('clock.table.setSchedule_text'));
                    $this->logText(["type" => self::page, "text" => $text]);
                    //返回
                    $json['warn'] = 2;

                }
            } else {
                //按周期排
                //获取工作日
                $clockRule = query('clock_rule', " id = '$info[clockRuleId]'");
                $workDay = query('work_day', " id = '$clockRule[workDayId]'");
                $workDayArr = json_decode($workDay['workDay'], true);

                $schedulerArr = json_decode($mx['scheduler'], true);
                if (is_array($schedulerArr)) {
                    $cycleNum = count($schedulerArr);//有几个班次为周期
                    $splitArr = explode('-', $date);
                    $nowDay = end($splitArr);//获取此月份第几天
                    $nowDay = $nowDay * 1;//转为数字
                    $days = date('t', strtotime($date));//此月总天数
                    $counter = 0;//
                    for ($i = 1; $i <= $days; $i++) {
                        $toDay = date('Y-m', strtotime($date)) . '-' . sprintf('%02d', $i);
                        if ($i >= $nowDay && in_array($toDay, $workDayArr)) {
                            //从当前点击的日期开始设置并跳过非工作日
                            $modelNum = $counter % $cycleNum;//除模，
                            //排班记录
                            $record = query('roster_schedule', " stid = '$staff[stid]' and toDay = '$toDay' and orderId = '$info[id]'");
                            if (empty($record['id'])) {
                                $field = [
                                    'id' => self::getId(),
                                    'orderId' => $info['id'],
                                    'stid' => $staff['stid'],
                                    'toDay' => $toDay,
                                    'rosterMxId' => $schedulerArr[$modelNum],
                                    'updateTime' => $this->time,
                                    'time' => $this->time
                                ];
                                static::insert(["table" => 'roster_schedule', "field" => $field]);
                            } else {
                                $field = [
                                    'toDay' => $toDay,
                                    'rosterMxId' => $schedulerArr[$modelNum],
                                ];
                                static::update(["table" => 'roster_schedule', "field" => $field, 'where' => " id = '$record[id]'"]);
                            }
                            $counter++;
                        }
                    }
                    $text = str_replace(['{{staffName}}', '{{name}}'], [$this->control['name'], $mx['name']], L('clock.table.setSchedule_log'));
                    $this->logText(["type" => self::page, "text" => $text]);
                }
                $json['warn'] = 2;
            }
        }
        $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&menu=schedule&date={$date}&id=" . $info['id'];
        return json_encode($json, 320);
    }

    /**
     * 获取弹出层
     * @return bool|string
     */
    public function getSelectSet()
    {
        $id = $this->post('id');
        $x = $this->post('pageX') - 100;
        $y = $this->post('pageY') - 30;
        //班次
        $rosterMx = find(array('table' => 'roster_detail', 'where' => " orderId = '$id' and type = 1 order by time asc"));
        $rosterHtml = '';
        foreach ($rosterMx['array'] as $val) {
            $rosterHtml .= "<li data-id='{$val['id']}' data-stid='{$this->post('stid')}' data-date='{$this->post('date')}' onclick='setSchedule(this)' data-type='1'>" . $val['name'] . "</li>";
        }
        $rosterHtml .= "<li data-id='rest' data-type='1' data-stid='{$this->post('stid')}' data-date='{$this->post('date')}' onclick='setSchedule(this)'>" . L('clock.table.xiu_xi') . "</li>";

        //周期
        $rosterMx = find(array('table' => 'roster_detail', 'where' => " orderId = '$id' and type = 2 order by time asc"));
        $cycleHtml = '';
        foreach ($rosterMx['array'] as $val) {
            $cycleHtml .= "<li data-id='{$val['id']}' data-stid='{$this->post('stid')}' data-date='{$this->post('date')}' data-type='2' onclick='setSchedule(this)'>" . $val['name'] . "</li>";
        }
        $ban_ci = L('clock.table.ban_ci');
        $cycle = L('clock.table.cycle');
        $json['data']['html'] = <<<efo
<div class="choiceDiv" style="top: {$y}px;left: {$x}px">
<div class="choiceDivNav"><ul><li class="show-li" data-name="choice-content" onclick="changeNav(this)">$ban_ci</li><li data-name="cycle-content" onclick="changeNav(this)">$cycle</li></ul></div>
<div class="choice-content showContent">
<ul>
{$rosterHtml}
</ul>
</div>
<div class="cycle-content">
<ul>
{$cycleHtml}
</ul>
</div>
</div>

efo;


        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        switch ($act) {
            case 'delScheduleMx':
                $act = 'del';
                $msg = L('clock.table.scpbzq');
                $title = self::table . 'DeleteCycleMx';
                $function = 'deleteScheduleMx';
                $form = self::page . 'OperateForm, scheduleForm';
                $power = '';
                break;
            case 'delMx':
                $act = 'del';
                $msg = L('clock.table.scpbbc');
                $title = self::table . 'DeleteShiftMx';
                $function = 'deleteMx';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                break;
            default:
                $act = 'del';
                $msg = L('clock.table.sch_del');
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('jon.other.permission_warn'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('clock.table.nmzscdzx');
        } elseif (empty($array)) {
            $json['warn'] = L('clock.table.nygsjdmzxzn');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] != '草稿') {
                    $warn = L('clock.table.draft');
                } else {
                    //删除待办事项
                    delete(array("table" => "backlog", "where" => " typeId = '$id' "));
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    //最后删除基本参数
                    delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
                    //返回
                    $warn = L('clock.table.sccg');
                    $x++;
                }
                $text .= str_replace(['{{team}}', '{{id}}'], [$info['team'], $info['id']], L('clock.table.sch_del_text')) . $warn . "。<br>";

            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('clock.table.sch_del_log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('clock.table.sch_del_warn'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 删除班次
     * @return bool|string
     */
    public function deleteMx()
    {
        $array = $this->post('mxId');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('clock.table.nmzscdzx');
        } elseif (empty($array)) {
            $json['warn'] = L('clock.table.nygsjdmzxzn');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $mx = query(self::tableMx, " id = '$id' ");
                //最后删除基本参数
                delete(array("table" => self::tableMx, "where" => " id = '$id' "));
                //返回
                $warn = L('clock.table.sccg');
                $x++;
                $text .= str_replace(['{{name}}', '{{id}}'], [$mx['name'], $mx['id']], L('clock.table.mx_del_text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('clock.table.mx_del_log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('clock.table.mx_del_warn'));
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }

    /**
     * 删除排班周期
     * @return bool|string
     */
    public function deleteScheduleMx()
    {
        $array = $this->post('scheduleId');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('clock.table.nmzscdzx');
        } elseif (empty($array)) {
            $json['warn'] = L('clock.table.nygsjdmzxzn');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $mx = query(self::tableMx, " id = '$id' ");
                //最后删除基本参数
                delete(array("table" => self::tableMx, "where" => " id = '$id' "));
                //返回
                $warn = L('clock.table.sccg');
                $x++;
                $text .= str_replace(['{{name}}', '{{id}}'], [$mx['name'], $mx['id']], L('clock.table.schMx_del_text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('clock.table.schMx_del_log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('clock.table.schMx_del_warn'));
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }
}

